package com.liver_cloud.service.mail;

import java.io.File;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liver_cloud.dao.mybatis.DaoSupport;
import com.liver_cloud.util.PageData;
import com.liver_cloud.util.StringUtil;

@Service
public class MailService {

	@Resource(name = "daoSupport")
	private DaoSupport dao;

	@Resource(name = "mailSender")
	private JavaMailSenderImpl senderImpl;

	public void saveAndsendTransferMail(JSONObject jsonObject)
			throws Exception {
		// TODO Auto-generated method stub
		senderImpl.setHost("smtp.exmail.qq.com");
		senderImpl.setDefaultEncoding("UTF-8");
		MimeMessage mailMessage = senderImpl.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,
				true);
		// 解析jsonObject
		JSONObject param = jsonObject.getJSONObject("param");
		// 转诊的内容集合
		JSONArray templateList = param.getJSONArray("templateList");
		String mailTo = param.getString("mailTo");		
		String patientId = param.getString("patientId");
		//根据patientId获取patientName，在user表里查询
		String patientName = 
				(String) dao.findForObject("PatientMapper.getPatientName", patientId);
		String subJect = param.getString("subJect");
		//主题直接按发件人发送的，不在使用工具类创建
		List<String> content = 
				StringUtil.createContent(patientName,templateList);
		//System.out.println(subJect);
		String code = param.getString("code");
		//发给谁
		messageHelper.setTo(mailTo);
		//谁发送
		messageHelper.setFrom("liver_care@liver-cloud.com");
		//邮件主题
		messageHelper.setSubject(subJect);
		//根据mailTo查询是否已经注册过
		PageData doctorInfo = 
				(PageData) dao.findForObject("DoctorMapper.findDoctorByEmail", mailTo);
		boolean ifRegisted = false;
		String doctorId = "";
		if(doctorInfo != null){
			ifRegisted = true;
			doctorId = doctorInfo.get("di_id").toString();
		}
		//System.out.println(doctorId+"doctorId");
		String htmlTxt = StringUtil.createHtmlTxt(code,patientName,ifRegisted,doctorId,patientId,content);
		System.out.println(htmlTxt);
		messageHelper.setText(htmlTxt, true);
		senderImpl.setUsername("liver_care@liver-cloud.com");
		senderImpl.setPassword("Admin123456");
		Properties prop = new Properties();
		prop.put("mail.smtp.auth", "true"); // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
		prop.put("mail.smtp.timeout", "25000");
		senderImpl.setJavaMailProperties(prop);
		// 发送邮件
		senderImpl.send(mailMessage);
		//System.out.println("邮件发送成功..");
	}

}
